import {View, Text, StyleSheet} from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as BackgroundFetch from 'expo-background-fetch';
import {useEffect, useState} from 'react';
import IconButton from '@/components/IconButton';
import {
  connectToDeviceByDeviceId, // 连接设备通过 id
  monitorDisConnect
} from '@/utils/ble';


const BLUETOOTH_TEST_TASK_NAME = 'background-test-task';
const deviceId:string = 'FD:88:7C:57:93:D2'
let reconnectTimer:any = null

// 这个方法不能写在 component内部
TaskManager.defineTask(BLUETOOTH_TEST_TASK_NAME, async () => {
  // 这里执行你的后台任务，比如更新计时器状态
  const now = Date.now();
  console.log(`aGot background fetch call at date: ${new Date(now).toISOString()}`);
  // Be sure to return the successful result type!
  gConnectBike()
  return BackgroundFetch.BackgroundFetchResult.NewData;
});
// 注册一个后台任务
async function registerBackgroundFetchAsync() {
  return BackgroundFetch.registerTaskAsync(BLUETOOTH_TEST_TASK_NAME, {
    minimumInterval: 60 * 0.2, // 进入后台运行多久后开始执行
    stopOnTerminate: false, // android only,
    startOnBoot: true, // android only
  });
}

// 注销后台任务
async function unregisterBackgroundFetchAsync() {
  return BackgroundFetch.unregisterTaskAsync(BLUETOOTH_TEST_TASK_NAME);
}

// 监听连接断开
function gonDisconnect() {
  monitorDisConnect(deviceId, (err) => {
    console.log('连接断开1')
    gtoReconnect()
  })
}

function gConnectBike() {
  // 连接蓝牙
  connectToDeviceByDeviceId(deviceId, (flag: boolean, characteristic: Characteristic) => {
    if(flag) {
      console.log(`连接成功`);
    } else {
      console.log('连接断开0')
    }
  })
}

// 设置一个计时器定时连接
function gtoReconnect() {
  if(reconnectTimer) {
    clearTimeout(reconnectTimer)
  }
  reconnectTimer = setTimeout(() => {
    gConnectBike()
  }, 10 * 1000)
}

export default function App() {
  const [isRegistered, setIsRegistered] = useState(false); // 是否注册后台任务
  const [status, setStatus] = useState(null);

  useEffect(() => {
    checkStatusAsync();
  }, []);

  const checkStatusAsync = async () => {
    const status = await BackgroundFetch.getStatusAsync();
    const isRegistered = await TaskManager.isTaskRegisteredAsync(BLUETOOTH_TEST_TASK_NAME);
    setStatus(status);
    setIsRegistered(isRegistered);
  };

  const toggleFetchTask = async () => {
    if (isRegistered) {
      await unregisterBackgroundFetchAsync();
    } else {
      await registerBackgroundFetchAsync();
    }

    checkStatusAsync();
  };

  return (
    <View>
      <View style={styles.screen}>
        <View style={styles.textContainer}>
          <Text>
            Background fetch status:{' '}
            <Text style={styles.boldText}>
              {status && BackgroundFetch.BackgroundFetchStatus[status]}
            </Text>
          </Text>
          <Text>
            Background fetch task name:{' '}
            <Text style={styles.boldText}>
              {isRegistered ? BLUETOOTH_TEST_TASK_NAME : 'Not registered yet!'}
            </Text>
          </Text>
        </View>
        <View style={styles.textContainer}></View>
        <View style={styles.btnBox}>
          <IconButton icon='check' label={isRegistered ? 'Unregister BackgroundFetch task' : 'Register BackgroundFetch task'} onPress={toggleFetchTask} />
        </View>
      </View>
    </View>
  );
}


const styles = StyleSheet.create({
  btnBox: {
    marginBottom: 20
  },
  screen: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textContainer: {
    margin: 10,
  },
  boldText: {
    fontWeight: 'bold',
  },
})